#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

const std::string HttpSep = "\r\n";
const std::string homepage = "index.html";
const std::string wwwroot = "./wwwroot";

class HttpRequest
{
public:
    HttpRequest():_req_blank(HttpSep), _path(wwwroot)
    {}

    bool GetLine(std::string& request, std::string* line)
    {
        int pos = request.find(HttpSep);
        if(pos == std::string::npos) return false;
        *line = request.substr(0, pos);
        request.erase(0, pos + HttpSep.size());
        return true;
    }
    void DeSerialize(std::string& request)
    {
        std::string line;
        bool flag = GetLine(request, &line);
        if(!flag) return;
        else _req_line = line;

        while(true)
        {
            flag = GetLine(request, &line);
            if(flag && line.empty())
            {
                _req_content = request;
                break;
            }
            else if(flag && !line.empty())
            {
                _req_hander.push_back(line);
            }
            else break;
        }
    }
    void PraseReqLine()
    {
        std::istringstream iss(_req_line);
        iss >> _method >> _url >> _http_version;

        if(_url == "/")
        {
            // _path += _url + homepage;
            _path += _url;
            _path += homepage;
        }
        else
        {
            _path += _url;
        }
    }
    void PraseSuffix()
    {
        int pos = _path.rfind(".");
        if(pos == std::string::npos) _suffix = ".html";
        else _suffix = _path.substr(pos);
    }
    void Prase()
    {
        PraseReqLine();
        PraseSuffix();
    }
    void HttpDebug()
    {
        std::cout << "--->" << "_req_line: " << _req_line << std::endl;
        std::cout << "--->" << "_method   " << _method << std::endl;
        std::cout << "--->" << "_url   " << _url << std::endl;
        std::cout << "--->" << "_http_version   " << _http_version << std::endl;
        std::cout << "--->" << "_path   " << _path << std::endl;
        std::cout << "--->" << "_suffix   " << _suffix << std::endl;
        
        for(auto& line : _req_hander)
            std::cout << "--->" << line << std::endl;
        std::cout << "--->"  << _req_blank << std::endl;
        std::cout << "--->"  << _req_content << std::endl;
    }

    std::string GetUrl() {return _url;}
    std::string GetPath() { return _path;}
    std::string GetSuffix() {return _suffix;}

private:
    std::string _req_line;
    std::vector<std::string> _req_hander;
    std::string _req_blank;
    std::string _req_content;

    std::string _method;
    std::string _url;
    std::string _http_version;
    std::string _path;
    std::string _suffix;
};